package com.tx.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.zip.Deflater;
import java.util.zip.Inflater;

/**
 * @author pyl
 * @date 2019/11/13
 * description
 **/
public class CompressUtil {

    public static byte[] uncompress(byte[] inputByte) throws IOException {
        int len = 0;
        Inflater infl = new Inflater();
        infl.setInput(inputByte);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] outByte = new byte[1024];
        try {
            while (!infl.finished()) {
                // 解压缩并将解压缩后的内容输出到字节输出流bos中
                len = infl.inflate(outByte);
                if (len == 0) {
                    break;
                }
                bos.write(outByte, 0, len);
            }
            infl.end();
        } catch (Exception e) {
            //
            e.printStackTrace();
        } finally {
            bos.close();
        }
        return bos.toByteArray();
    }

    public static String uncompressBase64(String inputStr) throws IOException {
        return new String(uncompress(Base64.getDecoder().decode(inputStr)));
    }

    public static byte[] compress(byte input[]) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Deflater compressor = new Deflater(1);
        try {
            compressor.setInput(input);
            compressor.finish();
            final byte[] buf = new byte[2048];
            while (!compressor.finished()) {
                int count = compressor.deflate(buf);
                bos.write(buf, 0, count);
            }
        } finally {
            compressor.end();
        }
        return bos.toByteArray();
    }

    public static String compress(String inputStr) throws IOException {
        return Base64.getEncoder().encodeToString(compress(inputStr.getBytes()));
    }


    public static void main(String[] args) throws Exception {


        String str = "{event: \"sub\", topic: [\"asset:4412\",\"orders:active:okex:spot:4412\"],data: {}, ts: 1236674,}";
        byte[] aa = compress(str.getBytes());
        String str1 = compress(str);
//        byte[] bb = uncompressBase64(Base64.getDecoder().decode(str1));
        String str2 = uncompressBase64(str1);
        System.out.println("压缩前：" + str);
        System.out.println("压缩后：" + str1);
        System.out.println("解压后：" + str2);

    }
}
